package com.heixiu.gallery2

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.google.gson.Gson
import kotlin.math.ceil

const val GALLERY_REQUEST_NORMAL = 0
const val GALLERY_REQUEST_NO_DATA = 1
const val GALLERY_REQUEST_NETWORK_ERROR = 2

class GalleryViewModel(application: Application) : AndroidViewModel(application) {
    private var _requestState = MutableLiveData<Int>()
    val requestState: LiveData<Int> get() = _requestState
    private var _photoList = MutableLiveData<List<PhotoItem>>()
    val photoList: LiveData<List<PhotoItem>> get() = _photoList // 相当于私有成员 _photoList 的getter方法
    private val keywords = arrayOf("car", "cat", "animal", "dog", "phone", "computer", "flower")

    private val perPage = 10
    private var isNewRequest = true
    private var currentPage = 1
    private var totalPage = 1
    private var isLoading = false
    private var currentKey = "cat"
    var scrollToTop = true

    private fun getUrl(): String =
        "https://pixabay.com/api/?key=16068472-49df3057d3f889611b1d79d33&q=${currentKey}&per_page=${perPage}&page=${currentPage}"

    fun resetData() {
        isNewRequest = true
        currentPage = 1
        totalPage = 1
        currentKey = keywords.random()
        scrollToTop = true
        fetchData()
    }

    // 请求数据
    fun fetchData() {
        if (isLoading) return
        if (currentPage > totalPage) {
            return
        }
        isLoading = true

        val stringRequest = StringRequest(
            Request.Method.GET,
            getUrl(),
            Response.Listener {
                with(Gson().fromJson(it, Pixabay::class.java)) {
                    totalPage = ceil(totalHits.toDouble() / perPage).toInt()
                    if (isNewRequest) {
                        _photoList.value = hits.toList()
                    } else {
                        _photoList.value = _photoList.value?.plus(hits.toList())
                    }
                }

                isLoading = false
                isNewRequest = false
                currentPage++

                if (currentPage > totalPage) {
                    _requestState.value = GALLERY_REQUEST_NO_DATA
                } else {
                    _requestState.value = GALLERY_REQUEST_NORMAL
                }
            },
            Response.ErrorListener {
                isLoading = false
                _requestState.value = GALLERY_REQUEST_NETWORK_ERROR
            }
        )
        VolleySingleton.getInstance(getApplication()).requestQueue.add(stringRequest)
    }
}
